<template>
  <ElDialog
    :title="dialogTitle"
    :model-value="visible"
    @update:model-value="handleCancel"
    width="800px"
    align-center
    class="menu-dialog"
    @closed="handleClosed"
  >
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="85px">
      <ElFormItem label="菜单类型">
        <ElRadioGroup v-model="menuType" :disabled="lockType">
          <ElRadioButton value="menu" label="menu">菜单</ElRadioButton>
          <ElRadioButton value="button" label="button">权限</ElRadioButton>
        </ElRadioGroup>
      </ElFormItem>

      <!-- 菜单表单 -->
      <template v-if="menuType === 'menu'">
        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="上级菜单" prop="parentId">
              <ElTreeSelect 
                v-model="form.parentId" 
                :data="processedMenuOptions" 
                :props="treeProps"
                placeholder="请选择上级菜单" 
                clearable 
                check-strictly
                :render-after-expand="false"
                node-key="value"
                style="width: 100%"
                @change="handleParentChange"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="菜单名称" prop="name">
              <ElInput v-model="form.name" placeholder="菜单名称" />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="路由地址" prop="path">
              <template #label>
                <span>路由地址</span>
                <el-tooltip 
                  v-if="parentMenuPath" 
                  :content="'完整路径: ' + fullMenuPath" 
                  placement="top"
                >
                  <i class="el-icon-question" style="margin-left: 4px; color: #409eff;"></i>
                </el-tooltip>
              </template>
              <div class="path-input">
                <span v-if="parentMenuPath" class="path-prefix">{{ parentMenuPath }}/</span>
                <ElInput 
                  v-model="form.path" 
                  placeholder="请输入路由地址" 
                  style="flex: 1"
                />
              </div>
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="组件路径" prop="component">
              <ElInput v-model="form.component" placeholder="组件路径" />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="前端权限" prop="webPerms">
              <ElInput v-model="form.webPerms" placeholder="前端权限标识" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="后端权限" prop="apiPerms">
              <ElInput v-model="form.apiPerms" placeholder="后端权限标识" />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="图标" prop="icon">
              <ArtIconSelector v-model="form.icon" :iconType="iconType" width="100%" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="菜单排序" prop="sort">
              <ElInputNumber
                v-model="form.sort"
                style="width: 100%"
                :min="1"
                controls-position="right"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="外部链接" prop="frameUrl">
              <ElInput v-model="form.frameUrl" placeholder="外部链接/内嵌地址(https://www.baidu.com)" />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElRow :gutter="20">
          <ElCol :span="6">
            <ElFormItem label="是否启用" prop="visibleFlag">
              <ElSwitch v-model="form.visibleFlag" :active-value="1" :inactive-value="0" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="6">
            <ElFormItem label="是否内嵌" prop="frameFlag">
              <ElSwitch v-model="form.frameFlag" :active-value="1" :inactive-value="0" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </template>

      <!-- 权限表单 -->
      <template v-if="menuType === 'button'">
        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="上级菜单" prop="parentId">
              <ElTreeSelect 
                v-model="form.parentId" 
                :data="processedMenuOptions" 
                :props="treeProps"
                placeholder="请选择上级菜单" 
                clearable 
                check-strictly
                :render-after-expand="false"
                node-key="value"
                style="width: 100%"
                @change="handleParentChange"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="权限名称" prop="authName">
              <ElInput v-model="form.authName" placeholder="权限名称" />
            </ElFormItem>
          </ElCol>
        </ElRow>
        
        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="前端权限" prop="webPerms">
              <ElInput v-model="form.webPerms" placeholder="前端权限标识" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="后端权限" prop="apiPerms">
              <ElInput v-model="form.apiPerms" placeholder="后端权限标识" />
            </ElFormItem>
          </ElCol>
        </ElRow>
        
        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="权限排序" prop="authSort">
              <ElInputNumber
                v-model="form.authSort"
                style="width: 100%"
                :min="1"
                controls-position="right"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </template>
    </ElForm>

    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="handleCancel">取 消</ElButton>
        <ElButton type="primary" @click="handleSubmit">确 定</ElButton>
      </span>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import type { FormInstance, FormRules } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { IconTypeEnum } from '@/enums/appEnum'
  import { formatMenuTitle } from '@/router/utils/utils'
  import type { AppRouteRecord } from '@/types/router'
  import {
    apiRbacMenuSaveDataUsingPost
  } from '@/api'

  interface MenuFormData {
    id: number
    name: string
    path: string
    webPerms: string
    apiPerms: string
    component: string
    icon: string
    visibleFlag: number
    sort: number
    frameFlag: number
    frameUrl: string
    disabledFlag: number
    authName: string
    authSort: number
    parentId: number
  }

  interface Props {
    visible: boolean
    type?: 'menu' | 'button'
    lockType?: boolean
    menuOptions?: any[]
    parentMenu?: any
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit', data: MenuFormData): void
  }

  const props = withDefaults(defineProps<Props>(), {
    visible: false,
    type: 'menu',
    lockType: false,
    menuOptions: () => [],
    parentMenu: undefined
  })

  const emit = defineEmits<Emits>()

  const formRef = ref<FormInstance>()
  const menuType = ref<'menu' | 'button'>('menu')
  const iconType = ref(IconTypeEnum.UNICODE)
  const loading = ref(false)

  const form = reactive<MenuFormData>({
    id: 0,
    name: '',
    path: '',
    webPerms: '',
    apiPerms: '',
    component: '',
    icon: '',
    visibleFlag: 1,
    sort: 1,
    frameFlag: 0,
    frameUrl: '',
    disabledFlag: 0,
    authName: '',
    authSort: 1,
    parentId: 0
  })

  /**
   * 路径拼接工具函数（处理多余斜杠）
   */
  const joinPath = (parent: string, child: string): string => {
    if (!parent) return child;
    if (!child) return parent;
    const p = parent.replace(/\/+$/, '');
    const c = child.replace(/^\/+/, '');
    return `${p}/${c}`;
  };

  /**
   * 正则表达式特殊字符转义
   */
  const escapeRegExp = (string: string): string => {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  };

  /**
   * 树形结构配置
   */
  const treeProps = {
    children: 'children',
    label: 'label',
    value: 'value'
  }

 /**
 * 处理后的菜单选项数据（确保符合ElTreeSelect要求的格式）
 */
const processedMenuOptions = computed(() => {
  if (!props.menuOptions || props.menuOptions.length === 0) {
    return [];
  }

  if (props.menuOptions.length > 0) {
    const firstItem = props.menuOptions[0];
    if (firstItem.children) {
      const processTreeNode = (node: any): any => {
        if (!node) return null;
        
        const processedNode = {
          ...node,
          label: node.menuName || node.label || '',
          value: (node.id !== undefined && node.id !== null) ? Number(node.id) : null,
        };

        if (node.children && Array.isArray(node.children) && node.children.length > 0) {
          processedNode.children = node.children.map(processTreeNode)
            .filter((child: any) => child !== null);
        } else {
          processedNode.children = [];
        }

        return processedNode;
      };

      const treeData = props.menuOptions.map(processTreeNode)
        .filter((node: any) => node !== null);
      
      return treeData;
    } else {

      const buildTreeFromPaths = (flatData: any[]) => {
        // 创建节点映射表
        const nodeMap: Record<string, any> = {};
        const roots: any[] = [];

        flatData.forEach(item => {
          nodeMap[item.menuPath] = {
            ...item,
            label: item.menuName || item.label || '',
            value: (item.id !== undefined && item.id !== null) ? Number(item.id) : null,
            children: []
          };
        });

        flatData.forEach(item => {
          const node = nodeMap[item.menuPath];
          if (!node) return;
          
          const parts = item.menuPath.split('/').filter(Boolean);
          if (parts.length === 0) {
            roots.push(node);
            return;
          }
          
          const parentPath = '/' + parts.slice(0, -1).join('/');
          const parent = nodeMap[parentPath];
          
          if (parent) {
            parent.children.push(node);
          } else {
            roots.push(node);
          }
        });
        
        return roots;
      };

      // 构建树形结构
      const treeData = buildTreeFromPaths(props.menuOptions);
      return treeData;
    }
  }

  return [];
});

  const parentMenuPath = computed(() => {
    if (!form.parentId || !props.menuOptions) return ''
    const parent = props.menuOptions.find(item => item.id === form.parentId)
    return parent ? parent.menuPath : ''
  })

  const fullMenuPath = computed(() => {
    if (!form.path) return parentMenuPath.value || ''
    return joinPath(parentMenuPath.value || '', form.path)
  })

  const dialogTitle = computed(() => {
    const type = menuType.value === 'menu' ? '菜单' : '权限'
    return `新建${type}`
  })

   const rules = computed<FormRules>(() => {
    const baseRules = {
      parentId: [{ required: false, message: '请选择上级菜单', trigger: 'change' }]
    };

    if (menuType.value === 'menu') {
      return {
        ...baseRules,
        name: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        path: [
          { required: true, message: '请输入路由地址', trigger: 'blur' },
          { 
            validator: (_, value, callback) => {
              if (value && value.includes(' ')) {
                callback(new Error('路由地址不能包含空格'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        webPerms: [{ required: false, message: '请输入前端权限标识', trigger: 'blur' }],
        apiPerms: [{ required: false, message: '请输入后端权限标识', trigger: 'blur' }],
        component: [{ required: false, message: '请输入组件路径', trigger: 'blur' }]
      };
    } else {
      return {
        ...baseRules,
        authName: [
          { required: true, message: '请输入权限名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        webPerms: [
          { required: true, message: '请输入前端权限标识', trigger: 'blur' },
          { pattern: /^[a-z0-9:_-]+$/, message: '格式应为小写字母、数字及_:组合', trigger: 'blur' }
        ],
        apiPerms: [
          { required: true, message: '请输入后端权限标识', trigger: 'blur' },
          { pattern: /^[a-z0-9:_-]+$/, message: '格式应为小写字母、数字及_:组合', trigger: 'blur' }
        ]
      };
    }
  })

  const handleParentChange = (parentId: number) => {
    if (!parentId) return;
    if (!form.path) {
      form.path = '';
      return;
    }

    const parent = props.menuOptions?.find(item => item.id === parentId);
    if (parent && parent.menuPath) {
      const parentPath = parent.menuPath.replace(/\/+$/, '');
      if (parentPath && form.path.startsWith(parentPath)) {
        const escapedParentPath = escapeRegExp(parentPath);
        form.path = form.path.replace(new RegExp(`^${escapedParentPath}/?`), '');
      }
    }
  }

  const resetForm = () => {
    formRef.value?.resetFields()
    Object.assign(form, {
      id: 0,
      name: '',
      path: '',
      webPerms: '',
      apiPerms: '',
      component: '',
      icon: '',
      visibleFlag: 1,
      sort: 1,
      frameFlag: 0,
      frameUrl: '',
      disabledFlag: 0,
      authName: '',
      authSort: 1,
      parentId: props.parentMenu?.id || 0
    })
  }

  const initForm = () => {
    resetForm()
    if (props.parentMenu?.id) {
      form.parentId = props.parentMenu.id
    }
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    // 输入值规范化处理
    form.name = form.name.trim();
    form.path = form.path.trim();
    form.webPerms = form.webPerms.trim();
    form.apiPerms = form.apiPerms.trim();

    await formRef.value.validate(async (valid) => {
      if (valid) {
        try {
          loading.value = true
          const menuData = {
            menuName: form.name,
            menuPath: fullMenuPath.value,
            menuComponent: form.component,
            menuIcon: form.icon,
            menuSort: form.sort,
            menuVisibleFlag: form.visibleFlag,
            menuFrameFlag: form.frameFlag,
            menuFrameUrl: form.frameUrl,
            menuWebPerms: form.webPerms,
            menuApiPerms: form.apiPerms,
            menuDisabledFlag: form.disabledFlag,
            menuParentId: form.parentId,
            menuType: menuType.value === 'menu' ? 1 : 2
          }

          // 添加调试信息
          console.log('[Menu Add] 提交的菜单数据:', menuData);

          if (menuType.value === 'menu' && !menuData.menuPath) {
            ElMessage.warning('请填写路由地址')
            loading.value = false
            return
          }
          
          const res = await apiRbacMenuSaveDataUsingPost({ body: menuData })
          
          console.log('[Menu Add] API响应结果:', res);
          
          // API响应处理
          if (res && typeof res === 'object' && 'id' in res && res.id > 0) {
            ElMessage.success('新增成功')
          } else if (res && typeof res === 'object' && 'msg' in res) {
            ElMessage.error(res.msg as string)
          } else {
            ElMessage.error('新增失败：未知响应格式')
          }

          if (res && typeof res === 'object' && 'id' in res) {
            emit('submit', { ...form })
            handleCancel()
          }
        } catch (error: any) {
          // 增强错误处理
          const errorMessage = error.message 
            ? `请求失败: ${error.message}` 
            : (error.toString ? error.toString() : '未知错误')
          console.error('菜单保存失败:', error)
          ElMessage.error(errorMessage)
        } finally {
          loading.value = false
        }
      }
    })
  }

  const handleCancel = () => {
    emit('update:visible', false)
  }

  const handleClosed = () => {
    resetForm()
  }

  watch(
    () => props.visible,
    (newVal) => {
      if (newVal) {
        menuType.value = props.type
        nextTick(() => {
          initForm()
        })
      }
    },
    { immediate: true } 
  )

  watch(
    () => props.type,
    (newType) => {
      if (props.visible) {
        menuType.value = newType
      }
    }
  )
</script>

<style scoped>
.path-prefix {
  font-size: 14px;
  color: #666;
  margin-right: 4px;
  white-space: nowrap;
}
.path-input {
  display: flex;
  align-items: center;
}
</style>